#include<bits/stdc++.h>
#include<windows.h>

using namespace std;
const int PageSize = 100; // Size of each page frame
const int PageCount = 5;  // Number of page frames

int v[5];
int now=0;
int getBlankPage(){
    int ans=0;
    while(true){
        if(v[now]==0){
            ans=now;
            now++;
            now=now%5;
            return ans;
        }else{
            v[now]=0;
            now++;
            now=now%5;
        }
    } 
}

int main(){
    // 创建内存映射文件对象
    HANDLE hMapFile=CreateFileMapping(
        INVALID_HANDLE_VALUE,
        NULL,
        PAGE_READWRITE,
        0,
        PageSize*PageCount,
        TEXT("memory")
    );

    //创建命名管道
    HANDLE memoryPipe=CreateNamedPipe(
        TEXT("\\\\.\\Pipe\\memoryPipe"),
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        1,
        1024,
        1024,
        0,
        NULL
    );
    if(memoryPipe==INVALID_HANDLE_VALUE){
        cerr<<"Create pipe failed: "<<GetLastError()<<endl;
        system("pause");
        return 0;
    }

    struct timeval tv;
    //等待客户端连接管道
    if(ConnectNamedPipe(memoryPipe,NULL)){

        //开始读取数据
        CHAR Buffer[101];
        CHAR blankPage[101];
        memset(blankPage,'\0',sizeof(blankPage));
        memset(Buffer,'\0',sizeof(Buffer));
        DWORD dwNumberOfBytesRead=0;
        DWORD dwNumberOfBytesWritten=0;

        for(int i=0;i<10;i++){
            //接收到worker的发送的页框号请求
            ReadFile(memoryPipe,Buffer,sizeof(Buffer),&dwNumberOfBytesRead,NULL);
            
            //向worker返回页框号
            memset(blankPage,'\0',sizeof(blankPage));
            snprintf(blankPage, sizeof(blankPage), "%d", getBlankPage());
            WriteFile(memoryPipe,blankPage,strlen(blankPage),&dwNumberOfBytesWritten,NULL);
        }
    }
    FlushFileBuffers(memoryPipe);
    DisconnectNamedPipe(memoryPipe);
	CloseHandle(memoryPipe);//关闭管道
	system("pause");
    return 0;
}